#!/usr/bin/env bash

[[ -n "$LKP_SRC" ]] || LKP_SRC=$(dirname $(dirname $(readlink -e -v $0)))

source "$LKP_SRC/lib/common.sh"
source "$LKP_SRC/lib/result.sh"
source "$LKP_SRC/lib/constant.sh"

check_rt()
{
	local path=${1%%/}
	local dn=$(dirname "$path")
	grep -q $path/stats.json $dn/matrix.json
}

# check whether it runs at local by the job.yaml in the result root
is_local_run()
{
       local path=${1%%/}

       is_rt "$path" && grep -q -s "^LKP_LOCAL_RUN: 1" "$path/job.yaml"
}

remove_index()
{
	local path
	for path; do
		path=$(abs_path "$path")
		[[ -d "$path" ]] || continue
		cleanup_path_record_from_result_root "$path"
	done
}

remove_paths()
{
	local path
	for path; do
		path=$(abs_path "$path")
		[[ -d "$path" ]] || continue
		path=$(readlink -e -v "$path")
		echo rm -fr "$path"
	done
}

remove_stale_links()
{
	local path
	local state_links

	for path; do
		path=$(abs_path "$path")
		if is_rt "$path"; then
			stale_links=$(find $(dirname $(dirname "$path")) -xtype l)
		elif is_mrt "$path"; then
			stale_links=$(find $(dirname "$path") -xtype l)
		fi

		rm -vf "$stale_links"
	done
}

remove_from_mrtts()
{
	local path
	local dir
	for path; do
		path=$(abs_path "$path")
		[[ -d "$path" ]] || continue
		for dir in $(find $path -type d); do
			is_mrt "$dir" && echo "$dir"
		done | $LKP_SRC/bin/lkp delete_mrts
	done
}

revert_unite_rt()
{
	local path
	for path; do
		if is_rt "$path" && check_rt "$path"; then
			if is_local_run "$path"; then
				$LKP_SRC/sbin/unite-stats -d "$path"
			else
				$LKP_SRC/bin/lkp reprocess -d "$path"
			fi
		fi
	done

	for path; do
		while is_rt "$path" && check_rt "$path" && ! is_local_run "$path"; do
			sleep 10
		done
	done
}

usage()
{
	cat >&2 <<-EOF
Usage:
	lkp $script_name [-y] <paths>
Example:
	lkp $script_name -y $RESULT_ROOT_DIR/xfstests/4HDD-ext4-ext4/lkp-ws02/debian-x86_64-2015-02-07.cgz/x86_64-rhel/gcc-4.9/v4.3/0/
EOF
	exit 1
}

script_name=$(basename $0)
[[ $# = 0 ]] && usage

opt_y=0
while getopts "y" opt; do
	case $opt in
		y ) opt_y=1; ;;
		? ) usage; ;;
	esac
done

shift $((OPTIND-1))

for path; do
	path=$(abs_path "$path")
	[[ -d "$path" ]] || {
		echo "The path does not exist: $path" >&2
		exit 1
	}
done

echo "The command to remove the result path are:"
remove_paths "$@"

if [[ $opt_y = 1 ]]; then
	answer="yes"
else
	echo -n "!!! Do you really want to do that? [No/yes]: "
	read answer
fi

if [[ $answer = "yes" ]]; then
	revert_unite_rt "$@"
	remove_from_mrtts "$@"
	remove_index "$@"
	remove_paths "$@" | bash
	remove_stale_links "$@"
fi
